<template>
  <div class="user-chat">
    <van-nav-bar
      class="app-nav-bar"
      title="小智同学"
      left-arrow
      @click-left="$router.back()"
    />
    <van-cell-group class="message-list">
      <van-cell
        :title="item.msg"
        :v-for="(item, index) in messages"
        :key="index"
      />
    </van-cell-group>
    <van-cell-group
      class="send-message-wrap" ref="message-list">
      <van-field
        v-model="message"
        placeholder="请输入消息"
        :border="false"
      />
      <van-button
      class="send-btn"
        type="primary"
        size="small"
        @click="onSend"
      >
        发送
      </van-button>
    </van-cell-group>
  </div>
</template>

<script>
import io from 'socket.io-client'
import { getItem, setItem } from '@/utils/storage'
// 发送消息
// socket.emit('消息类型', 消息内容)
// socket.on('消息类型', function (data) {data消息})
export default {
  name: 'UserChat',
  data () {
    return {
      message: '',
      socket: null,
      messages: getItem('chat-messages') || []
    }
  },
  created () {
    // 建立连接
    const socket = io('http://ttapi.research.itcast.cn/')
    this.socket = socket
    socket.on('connect', function () {
      // console.log('连接建立成功了')
    })

    // 断开连接了
    socket.on('disconnect', () => {
      // console.log('断开连接了')
    })

    // 监听message事件，接受服务端消息
    socket.on('message', data => {
      this.messages.push(data)
    })
  },
  mounted () {
    this.scrollToBottom()
  },
  watch: {
    messages () {
      setItem('chat-messages', this.messages)

      this.$nextTick(() => {
        this.scrollToBottom()
      })
    }
  },
  methods: {
    onSend () {
      const data = {
        msg: this.message,
        timestamp: Date.now()
      }
      this.socket.emit('message', data)
      this.messages.push(data)
      this.message = ''
    },
    scrollToBottom () {
      const list = this.$refs['message-list']
      list.scrollTop = list.scrollHeight
    }
  }
}
</script>

<style lang="less" scoped>
  .message-list {
    position: fixed;
    left: 0;
    right: 0;
    top: 46px;
    bottom: 44px;
    overflow-y: auto;
  }
  .send-message-wrap {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    padding: 0 14px;
    align-items: center;
    .send-btn {
      width:80px;
    }
  }
</style>
